package group.cyfc.studygo.service;

import group.cyfc.studygo.dao.GatewayRepository;
import group.cyfc.studygo.dao.UserRecordRepository;
import group.cyfc.studygo.dao.UserRepository;
import group.cyfc.studygo.dto.JsonResult;
import group.cyfc.studygo.entity.Gateway;
import group.cyfc.studygo.entity.User;
import group.cyfc.studygo.entity.UserRecord;
import group.cyfc.studygo.util.SnowflakeIdWorker;
import group.cyfc.studygo.vo.UserRecordVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserRecordService {
    @Autowired
    private UserRecordRepository userRecordRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private GatewayRepository gatewayRepository;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 保存或更新用户的闯关记录
     * 当用户已有对应类型关卡的闯关记录时进行更新
     * @param userRecordVo
     */
    public JsonResult saveRecord(UserRecordVo userRecordVo){
        User user = userRepository.findByIdAndIsDel(Long.valueOf(userRecordVo.getUserId()),false);
        if(user==null){
            return new JsonResult().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"error",userRecordVo.getUserId());
        }
        Gateway gateway = gatewayRepository.findByIdAndIsDel(Long.valueOf(userRecordVo.getGatewayId()),false);
        if(gateway==null){
            return new JsonResult().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"error",userRecordVo.getGatewayId());
        }
        UserRecord userRecord = userRecordRepository.findByUserIdAndGradeAndSubjectAndIsDel(
                Long.valueOf(userRecordVo.getUserId()),userRecordVo.getGrade(),userRecordVo.getSubject(),false
        );
        try {
            if(userRecord==null){
                UserRecord newRecord = new UserRecord();
                BeanUtils.copyProperties(userRecordVo,newRecord);
                newRecord.setUserId(Long.valueOf(userRecordVo.getUserId()));
                newRecord.setGatewayId(Long.valueOf(userRecordVo.getGatewayId()));
                newRecord.setId(snowflakeIdWorker.nextId());
                newRecord.setCreateBy(1L);
                newRecord.setCreateAt(new Date());
                newRecord.setUpdateBy(1L);
                newRecord.setCreateAt(new Date());
                userRecordRepository.save(newRecord);
            }else {
                userRecordRepository.updateRecord(userRecord.getId(),Long.valueOf(userRecordVo.getGatewayId()));
            }
            return new JsonResult().ok("ok");
        }catch (Exception e){
            return new JsonResult().serverError("error");
        }

    }
}
